﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Dude.MLS;
using System.ComponentModel;
using System.Xml;

namespace Dude.Data.Meta
{
    [Serializable]
    [XmlRoot(ElementName = "datamodel", Namespace = "http://dude.mystiq.org/Schemas/2009/DatabaseModel.xsd")]
    public class DataModel : ITreeReconstruct, IVisitedDataModel
    {
        public DataModel()
        {
            Databases = new List<DatabaseInfo>();
            Connections = new List<DatabaseConnectionInfo>();
            DisplayName = new MLString();
            Description = new MLString();
            LongDescription = new MLString();
        }

        [Category("Localization")]
        [XmlElement("display")]
        public MLString DisplayName { get; set; }

        [Category("Localization")]
        [XmlElement("desc")]
        public MLString Description { get; set; }

        [Category("Localization")]
        [XmlElement("longdesc")]
        public MLString LongDescription { get; set; }

        [Category("Database")]
        [XmlElement("connection")]
        public List<DatabaseConnectionInfo> Connections { get; set; }

        [Category("Database")]
        [XmlElement("database")]
        public List<DatabaseInfo> Databases { get; set; }

        #region ITreeReconstruct Members

        public void ReconstructTree(object parent)
        {
            foreach (ITreeReconstruct r in Databases)
            {
                r.ReconstructTree(this);
            }
        }

        #endregion

        /// <summary>
        /// Load model from file
        /// </summary>
        /// <param name="url">URL or file name of stored object</param>
        public static DataModel Load(string url)
        {
            using (XmlReader xreader = XmlReader.Create(url))
            {
                XmlSerializer xserializer = new XmlSerializer(typeof(DataModel));
                DataModel dm = (DataModel)xserializer.Deserialize(xreader);
                dm.ReconstructTree(null);
                return dm;
            }
        }

        public void Save(string filename)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.Encoding = Encoding.UTF8;
            using (XmlWriter xwriter = XmlWriter.Create("table.xml", settings))
            {
                XmlSerializer xserializer = new XmlSerializer(typeof(DataModel));
                xserializer.Serialize(xwriter, this);
            }
        }

        public override string ToString()
        {
            return DisplayName.ToString();
        }

        #region IVisitedDataModel Members

        public void VisitedDataModel(IDataModelVisitor visitor)
        {
            visitor.VisitDataModel(this);
        }

        #endregion
    }
}
